package com.wjf.birdfish.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


/*****
 * Ftp辅助类
 * @author lzp
 * @deprecated
 * @see com.tydic.ftp.SRMFileUtil
 */
public class FtpUtil {
	
	public final static Log LOG = LogFactory.getLog(FtpUtil.class);
	public final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	private final static int BUFFER_SIZE = 8192;

	private String userName; // FTP 登录用户名
	private String password; // FTP 登录密码
	private String ip; // FTP 服务器地址IP地址
	private int port; // FTP 端口
	private int connectionTimeOut;
	private int readTimeOut;
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getConnectionTimeOut() {
		return connectionTimeOut;
	}

	public void setConnectionTimeOut(int connectionTimeOut) {
		this.connectionTimeOut = connectionTimeOut;
	}

	public int getReadTimeOut() {
		return readTimeOut;
	}

	public void setReadTimeOut(int readTimeOut) {
		this.readTimeOut = readTimeOut;
	}

	private Properties property = null; // 属性集
	private String configFile = null; // 配置文件的路径名
	public String getConfigFile() {
		return configFile;
	}

	private FTPClient ftpClient = null; // FTP 客户端代理

	/**
	 * 上传单个文件
	 * 
	 * @param localFile
	 *            --本地文件路径
	 * @param serverDirectory 服务器路径
	 * @return true 上传成功，false 上传失败
	 */
	public synchronized boolean uploadFile(File localFile,String serverDirectory) {
		//判断参数：localFile
		if(localFile == null ){
			LOG.error("FtpUtil:uploadFile:input localFile is NULL ");
			return false;
		}
		
		if(!localFile.isFile() ){
			LOG.error("FtpUtil:uploadFile:input localFile is not a file ");
			return false;
		}
		
		//判断参数：serverDirectory
		if(serverDirectory == null || "".equals(serverDirectory)){
			LOG.error("FtpUtil:uploadFile:input serverDirectory is NULL ");
			return false;
		}
		
		LOG.info("FtpUtil:uploadFile:input localFile=" + localFile.getAbsolutePath() + ",serverDirectory=" + serverDirectory);
		boolean flag = true;
		InputStream input = null;
		try {
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

			createDirectory(serverDirectory);
			
			String fileName = localFile.getName();
			String[] serverFileList = listRemoteFiles(fileName);
			Date now = new Date();
			String endFlag = "_bak_"+sdf.format(now);
			if(serverFileList !=null && serverFileList.length > 0 ){ //服务器有相应文件，则需要进行备份
				boolean reNameFlag = ftpClient.rename(fileName, fileName + endFlag);
				LOG.info("FtpUtil:uploadFile:bak fileName=" + fileName +"  rename  " +fileName + endFlag);
				if(!reNameFlag){ //重命名失败，返回
					LOG.error("FtpUtil:uploadFile:bak file error,fileName=" + fileName +"  rename  " +fileName + endFlag);
					return false;
				}
			}
			ftpClient.changeWorkingDirectory(serverDirectory);
			input = new FileInputStream(localFile);
			flag = ftpClient.storeFile(fileName, input);
			if(!flag){ //上传失败，将文件重命名回来
				LOG.error("FtpUtil:uploadFile:upload error fileName");
				boolean bakReName = ftpClient.rename(fileName + endFlag,fileName);
				LOG.info("FtpUtil:uploadFile:recover fileName=" +fileName + endFlag +"  rename  " + fileName);
				if(!bakReName){
					LOG.error("FtpUtil:uploadFile:recover error fileName=" +fileName + endFlag +"  rename  " + fileName);
				}
			}
		} catch (Exception e) {
			LOG.error("FtpUtil:uploadFile:error",e);
			flag=false;
		}finally{
			if(input != null ){
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	public void setFtpClient(FTPClient ftpClient) {
		this.ftpClient = ftpClient;
	}

	public void createDirectory(String serverDirectory) throws IOException {
		serverDirectory = serverDirectory.replace("//", "/");
		String[] dirs = serverDirectory.split("/");
		ftpClient.changeWorkingDirectory("/");
		int index=0;
		for(int i =0;i<dirs.length;i++){
			String dir = dirs[i];
			index += dir.length()+1;
			if(StringUtils.isNotBlank(dir)){
				String mkdir = serverDirectory.substring(0,index);
				ftpClient.makeDirectory(mkdir); //创建上传目录
			}
			
		}
		
		ftpClient.changeWorkingDirectory(serverDirectory);
		
	}

	/**
	 * 上传文件夹至ftp
	 * 
	 * @param localFile
	 *            --本地文件路径
	 * @param serverDirectory 服务器路径
	 * @return true 上传成功，false 上传失败
	 */
	public synchronized boolean uploadFiles(File localFile,String serverDirectory) {
		//判断参数：localFile
		if(localFile == null ){
			LOG.error("FtpUtil:uploadFile:input localFile is NULL ");
			return false;
		}
		
		if(!localFile.isDirectory() ){
			LOG.error("FtpUtil:uploadFile:input localFile is not a Directory ");
			return false;
		}
		
		//判断参数：serverDirectory
		if(serverDirectory == null || "".equals(serverDirectory)){
			LOG.error("FtpUtil:uploadFile:input serverDirectory is NULL ");
			return false;
		}
		
		LOG.info("FtpUtil:uploadFile:input localFile=" + localFile.getAbsolutePath() + ",serverDirectory=" + serverDirectory);
		boolean flag = true;
		int successCounts = 0;
		InputStream input = null;
		String[] fileNames = localFile.list();
		boolean succ = false;
		try {
			for(String fileName : fileNames){
				File upload = new File(localFile.getAbsolutePath()+ "/" +fileName);
				if(upload.isFile()){
					succ = uploadFile(upload,serverDirectory);
					if(!succ){
						return false;
					}
				}else{
					serverDirectory = serverDirectory + "/" + localFile.getName()+ "/" +fileName+"/";
					succ = uploadFiles(upload,serverDirectory);
					if(!succ){
						return false;
					}
				}
			}
			/*ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

			ftpClient.changeWorkingDirectory(File.separator);
			ftpClient.makeDirectory(serverDirectory); //创建上传目录
			ftpClient.changeWorkingDirectory(serverDirectory);
			for(String fileName :fileNames){
				String[] serverFileList = listRemoteFiles(fileName);
				Date now = new Date();
				String endFlag = "_bak_"+sdf.format(now);
				if(serverFileList !=null && serverFileList.length > 0 ){ //服务器有相应文件，则需要进行备份
					boolean reNameFlag = ftpClient.rename(fileName, fileName + endFlag);
					LOG.info("FtpUtil:uploadFile:bak fileName=" + fileName +"  rename  " +fileName + endFlag);
					if(!reNameFlag){ //重命名失败，返回
						LOG.error("FtpUtil:uploadFile:bak file error,fileName=" + fileName +"  rename  " +fileName + endFlag);
						return false;
					}else{
						successCounts++;
					}
				}
				ftpClient.changeWorkingDirectory(serverDirectory);
				input = new FileInputStream(localFile);
				flag = ftpClient.storeFile(fileName, input);
				if(!flag){ //上传失败，将文件重命名回来
					LOG.error("FtpUtil:uploadFile:upload error fileName");
					boolean bakReName = ftpClient.rename(fileName + endFlag,fileName);
					LOG.info("FtpUtil:uploadFile:recover fileName=" +fileName + endFlag +"  rename  " + fileName);
					if(!bakReName){
						LOG.error("FtpUtil:uploadFile:recover error fileName=" +fileName + endFlag +"  rename  " + fileName);
					}
				}
			}*/
			
		} catch (Exception e) {
			LOG.error("FtpUtil:uploadFile:error",e);
		}finally{
			if(input != null ){
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if(successCounts == fileNames.length){
			flag = true;
		}
		
		return flag;
	}
	/**
	 * 列出服务器上文件和目录
	 * 
	 * @param regStr
	 *            --匹配的正则表达式
	 */
	public String[] listRemoteFiles(String regStr) {
		String[] files =null;
		try {
			files = ftpClient.listNames(regStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return files;
	}

	/**
	 * 列出Ftp服务器上的所有文件和目录
	 */
	public String[] listRemoteAllFileNames() {
		String[] files =null;
		try {
			files = ftpClient.listNames();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return files;
	}
	
	/**
	 * 列出Ftp服务器上的所有文件和目录
	 */
	public FTPFile[] listRemoteAllFiles() {
		FTPFile[] files =null;
		try {
			files = ftpClient.listFiles();
		} catch (Exception e) {
			LOG.error("FtpUtil:listRemoteAllFiles:error",e);
		}
		return files;
	}

	/**
	 * 关闭连接
	 */
	public void closeConnect() {
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置配置文件
	 * 
	 * @param configFile
	 */
	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}

	/**
	 * 设置传输文件的类型[文本文件或者二进制文件]
	 * 
	 * @param fileType
	 *            --BINARY_FILE_TYPE、ASCII_FILE_TYPE
	 * 
	 */
	public void setFileType(int fileType) {
		try {
			ftpClient.setFileType(fileType);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 扩展使用
	 * 
	 * @return ftpClient
	 */
	protected FTPClient getFtpClient() {
		return ftpClient;
	}

	/**
	 * 设置参数
	 * 
	 * @param configFile
	 *            --参数的配置文件
	 */
	public void setArg(String configFile) {
		property = new Properties();
		BufferedInputStream inBuff = null;
		try {
			File file = new File(configFile);
			inBuff = new BufferedInputStream(new FileInputStream(file));
			property.load(inBuff);
			userName = property.getProperty("username");
			password = property.getProperty("password");
			ip = property.getProperty("ip");
			port = Integer.parseInt(property.getProperty("port"));
		} catch (FileNotFoundException e1) {
			LOG.debug("配置文件 " + configFile + " 不存在！");
		} catch (IOException e) {
			LOG.debug("配置文件 " + configFile + " 无法读取！");
		}
	}
	
	
	public FtpUtil(){}
	
	
	public boolean connectServer(String ip, int port, String userName,String password) {
		this.ip = ip;
		this.port=port;
		this.userName=userName;
		this.password=password;
//		this.connectionTimeOut=Integer.parseInt(CommonEnv.getFtpConnectionTime());
//		this.readTimeOut =Integer.parseInt(CommonEnv.getFtpReadTime());
		
		
		return connectServer();
	}
	/**
	 * 连接到服务器
	 * 
	 * @return true 连接服务器成功，false 连接服务器失败
	 */
	public boolean connectServer() {
		boolean flag = true;
		if (ftpClient == null) {
			int reply;
			try {
				ftpClient = new FTPClient();
				ftpClient.setControlEncoding("GBK");
				ftpClient.setDefaultPort(port);
				ftpClient.setConnectTimeout(connectionTimeOut);
				ftpClient.configure(getFtpConfig());
				ftpClient.connect(ip);
				ftpClient.login(userName, password);
				ftpClient.setDefaultPort(port);
				reply = ftpClient.getReplyCode();
				ftpClient.setDataTimeout(this.readTimeOut);

				if (!FTPReply.isPositiveCompletion(reply)) {
					ftpClient.disconnect();
					LOG.error("FTP server refused connection.");
					flag = false;
				}
			} catch (SocketException e) {
				flag = false;
				e.printStackTrace();
				LOG.error("登录ftp服务器 " + ip + " 失败,连接超时！",e);
			} catch (IOException e) {
				flag = false;
				e.printStackTrace();
				LOG.error("登录ftp服务器 " + ip + " 失败，FTP服务器无法打开！",e);
			}
		}
		return flag;
	}

	/**
	 * 进入到服务器的某个目录下
	 * 
	 * @param directory
	 */
	public void changeWorkingDirectory(String directory) {
		try {
			ftpClient.changeWorkingDirectory(directory);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 返回到上一层目录
	 */
	public void changeToParentDirectory() {
		try {
			ftpClient.changeToParentDirectory();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 重命名文件
	 * 
	 * @param oldFileName
	 *            --原文件名
	 * @param newFileName
	 *            --新文件名
	 */
	public void renameFile(String oldFileName, String newFileName) {
		try {
			ftpClient.rename(oldFileName, newFileName);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 设置FTP客服端的配置--一般可以不设置
	 * 
	 * @return ftpConfig
	 */
	private FTPClientConfig getFtpConfig() {
		FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
		ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
		return ftpConfig;
	}

	/**
	 * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码
	 * 
	 * @param obj
	 * @return ""
	 */
	public String iso8859togbk(Object obj) {
		try {
			if (obj == null)
				return "";
			else
				return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 在服务器上创建一个文件夹
	 * 
	 * @param dir
	 *            文件夹名称，不能含有特殊字符，如 \ 、/ 、: 、* 、?、 "、 <、>...
	 */
	public boolean makeDirectory(String dir) {
		boolean flag = true;
		try {
			flag = ftpClient.makeDirectory(dir);
			if (flag) {
				LOG.debug("make Directory " + dir + " succeed");

			} else {

				LOG.debug("make Directory " + dir + " false");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 删除一个文件
	 */
	public boolean deleteFile(String filename) {
		boolean flag = true;
		try {
			String path = filename.substring(0,filename.lastIndexOf("/"));
			ftpClient.changeWorkingDirectory(path);
			flag = ftpClient.deleteFile(filename);
		} catch (IOException ioe) {
			LOG.error("FtpUtil:deleteFile:error,filename" + filename,ioe);
		}
		if (flag) {
			LOG.debug("FtpUtil:deleteFile:success,filename" + filename);
		} else {
			LOG.error("FtpUtil:deleteFile:error,filename" + filename);
		}
		return flag;
	} 

	/**
	 * 删除目录
	 * @param path
	 *            目录名
	 * @return true：成功，false：失败
	 * @see
	 */
	public boolean deleteDirectory(String pathname) {
		LOG.debug("FtpUtil:deleteDirectory:begin,pathname" + pathname);
		boolean success = false;
		try {
			ftpClient.changeWorkingDirectory(pathname);
			FTPFile[] ftpFiles = ftpClient.listFiles(); //目录 + 文件
			for(FTPFile ftpFile : ftpFiles){
				if(ftpFile.isFile()){
					boolean flag = deleteFile(pathname +"/"+ ftpFile.getName());
					if(flag == false){
						return false;
					}
				}else{
					boolean flag = deleteDirectory(pathname +"/"+ ftpFile.getName());
					if(flag == false){
						return false;
					}
				}
			}
			success = ftpClient.removeDirectory(pathname); //删除空目录
			
		} catch (IOException ioe) {
			LOG.debug("FtpUtil:deleteDirectory:error,pathname" + pathname,ioe);
			return false;
		}
		
		LOG.debug("FtpUtil:deleteDirectory:end"); 
		return success;
	} 
	
	
	/** 
     * 下载文件 
     * 
     * @param remoteFileName             --服务器上的文件名 
     * @param localFileName              --本地文件名 
     * @return true 下载成功，false 下载失败 
     */ 
    public boolean loadFile(String remoteFileName, String localFileName) {
		boolean flag = true;
		// 下载文件
		BufferedOutputStream buffOut = null;
		try {
			buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
			flag = ftpClient.retrieveFile(remoteFileName, buffOut);
		} catch (Exception e) {
			LOG.error("FtpUtil:loadFile:error,remoteFileName"+remoteFileName+",localFileName"+localFileName, e);
			return false;
		} finally {
			try {
				if (buffOut != null)
					buffOut.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return flag;
	} 
	
    public InputStream getInputStream(String srcFile){
    	try {
			return new BufferedInputStream(ftpClient.retrieveFileStream(srcFile),BUFFER_SIZE);
		} catch (IOException e) {
			LOG.error("FtpUtil:getInputStream:error,srcFile="+srcFile,e);
			return null;
		}
    }
    
    public OutputStream getOutputStream(String destFile){
    	try {
			OutputStream os= ftpClient.storeFileStream(destFile);
			FilterOutputStream out = new FilterOutputStream(new BufferedOutputStream(os,BUFFER_SIZE));
			try {
				out.flush();
			} catch (Exception ex) {
			    LOG.error("FtpUtil:getOutputStream:error,flush error", ex);
				throw new IOException("failed to create OutputStream.");
			}
			return out;
		} catch (Exception e) {
			LOG.error("FtpUtil:getOutputStream:error,destFile="+destFile,e);
			e.printStackTrace();
			return null;
		}
    }
    /***
     * 
     * @param srcFile 源文件
     * @param destFile 目的文件
     * @return
     */
    public boolean copyFile(String srcFile,String destFile){
    	boolean flag = false;
    	// 流操作，拷贝文件
		InputStream ins = null;
		OutputStream out = null;
		try {
			OutputStream os= ftpClient.storeFileStream(destFile);
			ins = new BufferedInputStream(ftpClient.retrieveFileStream(srcFile),BUFFER_SIZE);
			
			out = new FilterOutputStream(new BufferedOutputStream(os,BUFFER_SIZE));
			out.flush();
			int nch = 0;
			byte buff[] = new byte[BUFFER_SIZE];
			while ((nch = ins.read(buff, 0, BUFFER_SIZE)) != -1) {
				out.write(buff, 0, nch);
			}
			
			//out.flush();
			System.out.println("read content :" + out.toString());;
			
		} catch (IOException ex2) {
			ex2.printStackTrace();
		} finally {
			if(out !=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if(ins !=null){
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    	return flag;
    }
    
	public static void main(String[] args) {
		FtpUtil test = new FtpUtil();
		test.connectServer("132.42.33.89",21,"tomcat","passw0rd");
		/*test.connectServer("132.42.33.89",21,"tomcat","passw0rd");
		
		test.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输二进制文件
		test.uploadFile(new File("C:\\test\\1.xml"),"/home/tomcat/lzp/");
		test.deleteDirectory("/home/tomcat/lzp/");
		//test.deleteFile("/home/tomcat/lzp/1.xml_bak");
		
		test.closeConnect();// 关闭连接
*/	
		/*boolean succ = test.uploadFiles(new File("D:/services/AcctBalSer/"), "/home/tomcat/lzp/services/");	
		System.out.println(succ);*/
		
		
		/*try {
			test.createDirectory("/home/tomcat/lzp/11/22/33/44/55/66/77/88/99/");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		/*boolean succ = test.loadFile("/home/tomcat/lzp/11.txt","F:/srm_tmp//11.txt");
		System.out.println(succ);*/
		boolean succ = test.copyFile("/home/tomcat/lzp/11.txt", "/home/tomcat/lzp/1/2.txt");
		System.out.println(succ);
		
	}

}
